package com.giggle.mybatis.utils;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

import java.math.BigDecimal;
import java.sql.Types;

/**
 * @author guozichen
 * @date 2019/6/28 9:52
 */
public class MybatisJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    public MybatisJavaTypeResolver(){
        super();
        super.typeMap.put(-7, new JdbcTypeInformation("TINYINT", new FullyQualifiedJavaType(Integer.class.getName())));
        super.typeMap.put(3, new JdbcTypeInformation("DECIMAL", new FullyQualifiedJavaType(Long.class.getName())));
    }

    @Override
    public FullyQualifiedJavaType calculateJavaType(IntrospectedColumn introspectedColumn) {
        FullyQualifiedJavaType answer;
        JdbcTypeInformation jdbcTypeInformation = typeMap.get(introspectedColumn.getJdbcType());
        if (jdbcTypeInformation == null) {
            switch (introspectedColumn.getJdbcType()) {
                case Types.DECIMAL:
                case Types.NUMERIC:
                    if(introspectedColumn.getScale() > 0)
                    {//如果包含小数点则转换成float
                        answer = new FullyQualifiedJavaType(Float.class.getName());
                    }else{
                        if ( introspectedColumn.getLength() > 18
                                || forceBigDecimals) {
                            answer = new FullyQualifiedJavaType(BigDecimal.class
                                    .getName());
                        } else if (introspectedColumn.getLength() > 9) {
                            answer = new FullyQualifiedJavaType(Long.class.getName());
                        } else if (introspectedColumn.getLength() > 4) {
                            answer = new FullyQualifiedJavaType(Integer.class.getName());
                        } else {
                            answer = new FullyQualifiedJavaType(Short.class.getName());
                        }
                    }
                    break;
                case Types.NVARCHAR :
                    answer = new FullyQualifiedJavaType(String.class.getName());
                    break;
                case Types.TINYINT:
                    answer = new FullyQualifiedJavaType(Integer.class.getName());
                    break;
                default:
                    answer = null;
                    break;
            }
        } else {
            answer = jdbcTypeInformation.getFullyQualifiedJavaType();
        }
        return answer;
    }
}
